﻿Public Class frmSales
    Dim dsSales As DataSet
    Dim daSales As OleDb.OleDbDataAdapter
    Dim sql As String
    Dim able1Comma, able2Comma, able3Comma, able4Comma As String
    Dim autoCount As Boolean = True
    Dim curDt As DateTime = Now
    Dim salesPrdCdChangeActionOn As Boolean

    Private Sub frmSales_FormClosing(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.FormClosing
        salesPrdCdChangeActionOn = False
        gSessionKey = ""
    End Sub

    Private Sub frmSales_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Call gSubIconShow(Me)
        Call dbConnection()
        Call mkCmbOutCause()
        Call mkCmbProduct("")
        Call gSubMkCmbPayMethod(cmbIncMethod)
        Call mkCmbCompany("", cmbCompany)
        Call mkCmbMember("")
        Call gSubMkCmbFlag(cmbFlag)
        If gSessionKey <> "" Then
            txtSessionKey.Text = gSessionKey
            btnSalesAll.Enabled = False
            btnSaleCredit.Enabled = False
            btnPrdOut.Enabled = False
            btnAdd.Enabled = False
            btnSave.Enabled = False
        Else
            txtSessionKey.Text = curDt
            btnPrdOut.Enabled = False
            btnSalesAll.Enabled = True
            btnSaleCredit.Enabled = True
        End If
        Call gridRefresh()

        Dim os As OperatingSystem = Environment.OSVersion
        If Mid(os.ToString, 1, 22) = "Microsoft Windows NT 5" Then
            Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedDialog
        End If
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub cmbCause_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles cmbCause.KeyPress
        e.Handled = True
    End Sub

    Private Sub cmbCause_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbCause.SelectedIndexChanged
        If gSessionKey = "" Then
            If cmbCause.SelectedValue.ToString <> "판매" Then
                txtUnitPrice.Text = 0
                btnSalesAll.Enabled = False
                btnSaleCredit.Enabled = False
                btnPrdOut.Enabled = True
            Else
                btnPrdOut.Enabled = False
                btnSalesAll.Enabled = True
                btnSaleCredit.Enabled = True
                Call getUnitPirce()
            End If
            Call getAllPrice()
        End If
    End Sub

    Private Sub cmbPrdCd_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles cmbPrdCd.KeyPress
        e.Handled = True
    End Sub

    Private Sub cmbPrdCd_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbPrdCd.SelectedIndexChanged
        Call getUnitPirce()
        Call getEaOnBox()
        Call getAllPrice()
    End Sub

    Private Sub radB2C_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radB2C.CheckedChanged
        Call getUnitPirce()
        Call getAllPrice()
    End Sub

    Private Sub radB2B_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radB2B.CheckedChanged
        Call getUnitPirce()
        Call getAllPrice()
    End Sub

    Private Sub radSalesUnit1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radSalesUnit1.CheckedChanged
        Call getEaOnBox()
        Call getAllPrice()
    End Sub

    Private Sub radSalesUnit2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radSalesUnit2.CheckedChanged
        Call getEaOnBox()
        Call getAllPrice()
    End Sub

    Private Sub txtQty_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtQty.KeyPress
        If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
            e.Handled = True
            able1Comma = ""
        Else
            able1Comma = "ok"
        End If
    End Sub

    Private Sub txtQty_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtQty.KeyUp
        If able1Comma = "ok" Then
            gSubWithComma(txtQty)
        End If
    End Sub

    Private Sub txtQty_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtQty.Leave
        Call getEaOnBox()
        Call getAllPrice()
    End Sub

    Private Sub txtTotalQty_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtTotalQty.KeyPress
        If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
            e.Handled = True
            able2Comma = ""
        Else
            able2Comma = "ok"
        End If
    End Sub

    Private Sub txtTotalQty_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTotalQty.KeyUp
        If able2Comma = "ok" Then
            gSubWithComma(txtTotalQty)
        End If
    End Sub

    Private Sub txtDCRate_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtDCRate.Leave
        Call getAllPrice()
    End Sub

    Private Sub txtDCAmount_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtDCAmount.Leave
        Call getAllPrice()
    End Sub

    Private Sub txtTax_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtTax.Leave
        If txtTax.Text = 0 Then
            txtOrgAmount.Text = txtAmount.Text
        End If
    End Sub

    Private Sub txtTotalQty_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtTotalQty.Leave
        Call getAllPrice()
    End Sub

    Private Sub txtFindPrdNm_KeyUp(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtFindPrdNm.KeyUp
        Call mkCmbProduct(txtFindPrdNm.Text)
    End Sub

    Private Sub txtFindCompany_KeyUp(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtFindCompany.KeyUp
        Call gSubMkCmbCompany(txtFindCompany.Text, cmbCompany)
    End Sub

    Private Sub txtFindMemNm_KeyUp(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtFindMemNm.KeyUp
        Call mkCmbMember(txtFindMemNm.Text)
    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Call savePrdSale()
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Call savePrdSale()
    End Sub

    Private Sub grdSalesInfo_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdSalesInfo.CellClick
        If e.RowIndex = -1 Then
            Exit Sub
        End If
        If IsDBNull(grdSalesInfo.Rows(e.RowIndex).Cells(0).Value) = True Then
            Exit Sub
        End If
        Call salesInfo(grdSalesInfo.Rows(e.RowIndex).Cells(0).Value)

    End Sub

    Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click
        Call txtReset()
    End Sub

    Private Sub btnSalesAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSalesAll.Click
        Call saveAllPrdSale("withIncome")
    End Sub

    Private Sub btnPrdOut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrdOut.Click
        Call saveAllPrdSale("")
    End Sub

    Private Sub btnSaleCredit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaleCredit.Click
        Call saveAllPrdSale("withCredit")
    End Sub

    Private Sub btnAllNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAllNew.Click
        Call txtAllReset()
    End Sub

    Private Sub cmbCompany_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles cmbCompany.KeyPress
        e.Handled = True
    End Sub

    Private Sub cmbFlag_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles cmbFlag.KeyPress
        e.Handled = True
    End Sub

    Private Sub cmbIncMethod_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles cmbIncMethod.KeyPress
        e.Handled = True
    End Sub

    Private Sub cmbMember_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles cmbMember.KeyPress
        e.Handled = True
    End Sub

#Region "프로시져"

    Private Sub txtAllReset()
        lbGridCnt.Text = "총  0 건"
        lbSummery.Text = "결재 총합계 : 0"
        Dim curDt As DateTime = Now
        txtSessionKey.Text = curDt
        cmbIncMethod.SelectedValue = 0
        Call txtReset()
        Call gridRefresh()
        btnPrdOut.Enabled = False
        btnSalesAll.Enabled = True
        btnSaleCredit.Enabled = True
        btnAdd.Enabled = True
        btnSave.Enabled = True
    End Sub

    Private Sub gridRefresh()
        Call dbConnection()
        Dim addSql As String = ""
        Dim totalAmt As Double = 0

        dsSales = New DataSet
        sql = "SELECT A.seq, A.sessionKey, A.issueDt as 거래일, A.prdNm as 제품, A.amount as 결재금액, A.company as 거래처, B.memNm as 회원명, A.[output] as 수량, A.unitPrice as 단가, A.totalPrice as 총금액, A.orgAmount as 판매가, A.tax as 부가세, A.salesType as 방식, A.dcRate+'%' as 할인율, A.dcAmount as 할인금액,  A.prdCd, A.compCd " + _
            "   FROM (" + _
            "               SELECT A2.seq, A2.sessionKey, A2.prdCd, A2.prdNm, B2.company, A2.memId, A2.[output], A2.unitPrice, A2.totalPrice, A2.amount, A2.orgAmount, A2.tax, A2.salesType, A2.issueDt, A2.dcRate, A2.dcAmount, A2.compCd " + _
            "               FROM (" + _
            "                           SELECT A1.seq, A1.sessionKey, A1.prdCd, B1.prdNm, A1.compCd, A1.memId, A1.[output], A1.unitPrice, A1.totalPrice, A1.amount, A1.orgAmount, A1.tax, A1.salesType, A1.issueDt, A1.dcRate, A1.dcAmount  " + _
            "                           FROM tblPrdOutTMP A1 LEFT JOIN tblProduct B1 ON A1.prdCd=B1.prdCd " + _
            "                           WHERE A1.flag='Y' AND A1.sessionKey='" + txtSessionKey.Text + "' " + _
            "            ) A2 LEFT JOIN tblCompany B2 ON A2.compCd=B2.compCd " + _
            "    ) A LEFT JOIN tblMember B ON A.memId=B.memId"
        'MsgBox(sql)

        Try
            daSales = New OleDb.OleDbDataAdapter(sql, dbConn)
            daSales.Fill(dsSales, "SalesInfo")

            grdSalesInfo.DataSource = dsSales.Tables("SalesInfo")

            For c = 0 To dsSales.Tables("SalesInfo").Rows.Count - 1
                totalAmt = totalAmt + CDbl(dsSales.Tables("SalesInfo").Rows(c).Item(4))
            Next
            lbSummery.Text = "결재 총합계 : " + Format(CInt(totalAmt), "#,##0")
            lbGridCnt.Text = "총 : " + dsSales.Tables("SalesInfo").Rows.Count.ToString + "건"
            grdSalesInfo.Columns(4).Frozen = True

            dbConn.Close()
            Call setGridDesign()

        Catch err As ObjectDisposedException
            dbConn.Close()
            MsgBox(sql)

            MsgBox(err.Message, MsgBoxStyle.Critical, "오류")
        End Try
    End Sub


    Private Sub setGridDesign()

        grdSalesInfo.Columns(0).Visible = False
        grdSalesInfo.Columns(1).Visible = False
        grdSalesInfo.Columns(2).Width = "80"
        grdSalesInfo.Columns(2).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        grdSalesInfo.Columns(3).Width = "110"
        grdSalesInfo.Columns(3).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
        grdSalesInfo.Columns(4).Width = "90"
        grdSalesInfo.Columns(4).DefaultCellStyle.Format = "n0"
        grdSalesInfo.Columns(4).DefaultCellStyle.ForeColor = Color.Red
        grdSalesInfo.Columns(5).Width = "120"
        grdSalesInfo.Columns(5).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
        grdSalesInfo.Columns(6).Width = "80"
        grdSalesInfo.Columns(6).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

        grdSalesInfo.Columns(7).Width = "70"
        grdSalesInfo.Columns(7).DefaultCellStyle.Format = "n0"
        grdSalesInfo.Columns(8).Width = "90"
        grdSalesInfo.Columns(8).DefaultCellStyle.Format = "n0"
        grdSalesInfo.Columns(9).Width = "90"
        grdSalesInfo.Columns(9).DefaultCellStyle.Format = "n0"
        grdSalesInfo.Columns(10).Width = "90"
        grdSalesInfo.Columns(10).DefaultCellStyle.Format = "n0"
        grdSalesInfo.Columns(11).Width = "90"
        grdSalesInfo.Columns(11).DefaultCellStyle.Format = "n0"
        grdSalesInfo.Columns(12).Width = "70"
        grdSalesInfo.Columns(12).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        grdSalesInfo.Columns(13).Width = "70"
        grdSalesInfo.Columns(13).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        grdSalesInfo.Columns(14).Width = "90"
        grdSalesInfo.Columns(14).DefaultCellStyle.Format = "n0"
        grdSalesInfo.Columns(15).Visible = False
        grdSalesInfo.Columns(16).Visible = False

        With grdSalesInfo.DefaultCellStyle
            .Alignment = DataGridViewContentAlignment.MiddleRight

        End With

    End Sub

    '## 판매정보 상세
    Private Sub salesInfo(ByVal seq As String)
        sql = "SELECT seq, prdCd, [output], unitPrice, totalPrice, compCd, memId, dcRate, dcAmount, amount, orgAmount, tax, boxQty, salesType, issueDt, flag, cause FROM tblPrdOutTMP WHERE seq=" + seq
        'MsgBox(sql)

        Call dbConnection()
        dsSales = New DataSet
        daSales = New OleDb.OleDbDataAdapter(sql, dbConn)
        daSales.Fill(dsSales, "SalesInfo")

        txtReset()
        dbConn.Close()

        autoCount = False '## 자동계산 OFF

        txtTmpSeq.Text = seq
        cmbPrdCd.SelectedValue = dsSales.Tables("SalesInfo").Rows(0).Item(1)
        If IsDBNull(dsSales.Tables("SalesInfo").Rows(0).Item(2)) = False Then
            txtTotalQty.Text = dsSales.Tables("SalesInfo").Rows(0).Item(2)
            txtTotalQty.Text = Format(CInt(txtTotalQty.Text), "#,##0")
        End If
        If IsDBNull(dsSales.Tables("SalesInfo").Rows(0).Item(3)) = False Then
            txtUnitPrice.Text = dsSales.Tables("SalesInfo").Rows(0).Item(3)
            txtUnitPrice.Text = Format(CInt(txtUnitPrice.Text), "#,##0")
        End If
        If IsDBNull(dsSales.Tables("SalesInfo").Rows(0).Item(4)) = False Then
            txtTotalAmount.Text = dsSales.Tables("SalesInfo").Rows(0).Item(4)
            txtTotalAmount.Text = Format(CInt(txtTotalAmount.Text), "#,##0")
        End If
        If IsDBNull(dsSales.Tables("SalesInfo").Rows(0).Item(5)) = False Then
            cmbCompany.SelectedValue = dsSales.Tables("SalesInfo").Rows(0).Item(5)
        End If
        If IsDBNull(dsSales.Tables("SalesInfo").Rows(0).Item(6)) = False Then
            cmbMember.SelectedValue = dsSales.Tables("SalesInfo").Rows(0).Item(6)
        End If
        If IsDBNull(dsSales.Tables("SalesInfo").Rows(0).Item(7)) = False Then
            txtDCRate.Text = dsSales.Tables("SalesInfo").Rows(0).Item(7)
            txtDCRate.Text = Format(CInt(txtDCRate.Text), "#,##0")
        End If
        If IsDBNull(dsSales.Tables("SalesInfo").Rows(0).Item(8)) = False Then
            txtDCAmount.Text = dsSales.Tables("SalesInfo").Rows(0).Item(8)
            txtDCAmount.Text = Format(CInt(txtDCAmount.Text), "#,##0")
        End If
        If IsDBNull(dsSales.Tables("SalesInfo").Rows(0).Item(9)) = False Then
            txtAmount.Text = dsSales.Tables("SalesInfo").Rows(0).Item(9)
            txtAmount.Text = Format(CInt(txtAmount.Text), "#,##0")
        End If
        If IsDBNull(dsSales.Tables("SalesInfo").Rows(0).Item(10)) = False Then
            txtOrgAmount.Text = dsSales.Tables("SalesInfo").Rows(0).Item(10)
            txtOrgAmount.Text = Format(CInt(txtOrgAmount.Text), "#,##0")
        End If
        If IsDBNull(dsSales.Tables("SalesInfo").Rows(0).Item(11)) = False Then
            txtTax.Text = dsSales.Tables("SalesInfo").Rows(0).Item(11)
            txtTax.Text = Format(CInt(txtTax.Text), "#,##0")
        End If
        If IsDBNull(dsSales.Tables("SalesInfo").Rows(0).Item(12)) = False Then
            txtQty.Text = dsSales.Tables("SalesInfo").Rows(0).Item(12)
            If CInt(txtQty.Text) > 0 Then
                radSalesUnit2.Checked = True
            Else
                radSalesUnit1.Checked = True
                txtQty.Text = txtTotalQty.Text
            End If
            txtQty.Text = Format(CInt(txtQty.Text), "#,##0")
        End If
        If IsDBNull(dsSales.Tables("SalesInfo").Rows(0).Item(13)) = False Then
            If dsSales.Tables("SalesInfo").Rows(0).Item(13) = "도매" Then
                radB2B.Checked = True
            Else
                radB2C.Checked = True
            End If
        End If
        If IsDBNull(dsSales.Tables("SalesInfo").Rows(0).Item(14)) = False Then
            dpIssueDt.Text = dsSales.Tables("SalesInfo").Rows(0).Item(14)
        End If
        If IsDBNull(dsSales.Tables("SalesInfo").Rows(0).Item(16)) = False Then
            cmbCause.SelectedValue = dsSales.Tables("SalesInfo").Rows(0).Item(16)
        End If
        autoCount = True  '## 자동계산 ON
    End Sub

    Private Sub txtReset()

        Call mkCmbProduct("")
        'Call gSubMkCmbCompany("", cmbCompany)
        'Call mkCmbMember("")
        Call gSubMkCmbFlag(cmbFlag)
        cmbIncMethod.SelectedValue = 0

        txtQty.Text = 1
        txtTotalQty.Text = 1
        radB2C.Checked = True
        radSalesUnit1.Checked = True
        txtTotalAmount.Text = 0
        txtUnitPrice.Text = 0
        txtDCRate.Text = 0
        txtDCAmount.Text = 0
        txtAmount.Text = 0
        txtOrgAmount.Text = 0
        txtTax.Text = 0
        txtTmpSeq.Clear()
        'txtFindCompany.Clear()
        'txtFindMemNm.Clear()
        txtFindPrdNm.Clear()
    End Sub

    '## 판매정보 모두 저장
    Private Sub saveAllPrdSale(ByVal flag As String)
        Dim seq As String = ""
        Dim ttlAmount, ttlOrgAmount, ttlTax As Double
        Dim valArticle As String = ""
        Dim prdCd As String = ""
        Dim compCd As String = ""
        Dim valIncCd As String = ""
        Dim valIncomeDt As String = Format(Now, "yyyy-MM-dd").ToString
        Dim billCd As String = "0"
        Dim prdOutSeq As String = ""
        Dim valIncMethod As String = ""
        Dim valRestAmount As String = ""
        Dim rtnMsg As String = ""

        If grdSalesInfo.Rows.Count = 0 Then
            MsgBox("출고 또는 판매할 제품을 추가해 주세요.")
            txtFindPrdNm.Focus()
            Exit Sub
        End If
        If flag = "withIncome" Then
            If cmbIncMethod.SelectedValue.ToString = "0" Then
                MsgBox("결재방법을 선택해 주세요.")
                cmbIncMethod.Focus()
                Exit Sub
            End If
        ElseIf flag = "" Then
            rtnMsg = "출고가 완료 되었습니다."
        End If

        Call dbConnection()

        'If flag = "withCredit" Then
        '## 거래명세서 코드 구하기
        sql = "SELECT max(billCd)+1 as maxBillCd FROM tblPrdInOut"
        billCd = gAFieldValue(sql)
        'End If

        For i = 0 To grdSalesInfo.Rows.Count - 1
            seq = grdSalesInfo.Rows(i).Cells(0).Value.ToString
            ttlAmount = ttlAmount + grdSalesInfo.Rows(i).Cells(4).Value
            ttlOrgAmount = ttlOrgAmount + grdSalesInfo.Rows(i).Cells(10).Value
            ttlTax = ttlTax + grdSalesInfo.Rows(i).Cells(11).Value
            prdCd = grdSalesInfo.Rows(i).Cells(15).Value.ToString
            compCd = grdSalesInfo.Rows(i).Cells(16).Value.ToString
            sql = "SELECT MAX(seq)+1 FROM tblPrdInOut"
            prdOutSeq = gAFieldValue(sql)
            '## 제품 입출고 저장
            sql = "INSERT INTO tblPrdInOut (seq, sessionKey, prdCd, [output], unitPrice, totalPrice, compCd, memId, dcRate, dcAmount, amount, orgAmount, tax, boxQty, salesType, billCd, cause, issueDt, addDt, updateDt )" + _
                "SELECT '" + prdOutSeq + "', sessionKey, prdCd, [output], unitPrice, totalPrice, compCd, memId, dcRate, dcAmount, amount, orgAmount, tax, boxQty, salesType, '" + billCd + "', cause, issueDt, addDt, updateDt FROM tblPrdOutTMP WHERE seq=" + seq
            Call gSubSaveAction(sql, rtnMsg)
        Next

        If flag = "withCredit" Or flag = "withIncome" Then
            valArticle = gAFieldValue("SELECT prdNm FROM tblProduct WHERE prdCd=" + prdCd) + "외 " + (grdSalesInfo.Rows.Count - 1).ToString + "건 판매"
            valIncCd = gFnGetIncCd()
            If flag = "withIncome" Then
                valRestAmount = "0"
            Else
                valRestAmount = ttlAmount.ToString
                rtnMsg = "신용판매가 완료 되었습니다."
            End If
            '## 매출 정보 저장
            sql = "INSERT INTO tblIncome(incCd, accountCd, article, amount, orgAmount, tax, compCd, incomeDt, billCd, restAmount, remarks, addDt, flag) " + _
                "   VALUES(" + valIncCd + ",'18','" + valArticle + "','" + ttlAmount.ToString + "','" + ttlOrgAmount.ToString + "','" + ttlTax.ToString + _
                "','" + compCd + "','" & valIncomeDt & "','" + billCd + "','" + valRestAmount + "','판매에 의한 자동 등록','" & curDt & "','Y')"
            Call gSubSaveAction(sql, rtnMsg)
        End If

        If flag = "withIncome" Then
            '## 매출 결재처리
            valIncMethod = cmbIncMethod.SelectedValue.ToString
            sql = "INSERT INTO tblIncResult(incCd, amount, actionDt, bankDt, incMethod, remarks, flag, addDt) " + _
                "   VALUES(" + valIncCd + ",'" + ttlAmount.ToString + "','" + valIncomeDt + "','" + valIncomeDt + "','" + valIncMethod + "','판매에 의한 자동등록','Y','" + curDt + "')"
            Call gSubSaveAction(sql, "판매 및 입금 처리가 완료 되었습니다.")
        End If
        dbConn.Close()

        Call txtAllReset()

    End Sub

    '## 판매정보 임시저장
    Private Sub savePrdSale()

        Call dbConnection()
        Dim oleCmd As OleDb.OleDbCommand
        Dim oleTran As OleDb.OleDbTransaction
        Dim rtnMsg As String = ""
        Dim valPrdCd, valQty, valBoxQty, valSalesType, valTotalQty, valCmbCause, valUnitPrice, valTotalAmount, valDCRate, valDCAmount, valAmount, valOrgAmount, valTax, valCompCd, valMemId, valIssueDt, valCmbFlag, valSessionKey As String
        Dim curDt As DateTime = Now

        valPrdCd = cmbPrdCd.SelectedValue.ToString
        valCompCd = cmbCompany.SelectedValue.ToString
        valMemId = cmbMember.SelectedValue.ToString
        valCmbFlag = cmbFlag.SelectedValue.ToString
        valCmbCause = cmbCause.SelectedValue.ToString
        valQty = txtQty.Text
        valTotalQty = txtTotalQty.Text
        valTotalAmount = txtTotalAmount.Text
        valUnitPrice = txtUnitPrice.Text
        valDCRate = txtDCRate.Text
        valDCAmount = txtDCAmount.Text
        valAmount = txtAmount.Text
        valOrgAmount = txtOrgAmount.Text
        valTax = txtTax.Text
        valIssueDt = dpIssueDt.Text
        valSessionKey = txtSessionKey.Text
        If radB2B.Checked = True Then
            valSalesType = "도매"
        Else
            valSalesType = "소매"
        End If
        If radSalesUnit2.Checked = True Then
            valBoxQty = txtQty.Text
        Else
            valBoxQty = "0"
        End If

        If valPrdCd = "0" Then
            dbConn.Close()
            MsgBox("제품을 먼저 선택해 주세요")
            cmbPrdCd.Focus()
            Exit Sub
        End If
        If valTotalQty = "" Or valTotalQty = "0" Then
            dbConn.Close()
            MsgBox("총수량을 바르게 입력해 주세요")
            txtTotalQty.Focus()
            Exit Sub
        End If
        If valUnitPrice = "" Then
            dbConn.Close()
            MsgBox("단가를 바르게 입력해 주세요")
            txtUnitPrice.Focus()
            Exit Sub
        End If
        If valAmount = "" Then
            dbConn.Close()
            MsgBox("결재총액을 바르게 입력해 주세요")
            txtAmount.Focus()
            Exit Sub
        End If
        If valOrgAmount = "" Then
            dbConn.Close()
            MsgBox("판매가가를 바르게 입력해 주세요")
            txtOrgAmount.Focus()
            Exit Sub
        End If
        If valTax = "" Then
            dbConn.Close()
            MsgBox("부가세를 바르게 입력해 주세요")
            txtTax.Focus()
            Exit Sub
        End If

        If txtTmpSeq.Text = "" Then
            sql = "INSERT INTO tblPrdOutTMP(sessionKey, prdCd, [outPut], unitPrice, totalPrice, compCd, memId, dcRate, dcAmount, amount, orgAmount, tax, boxQty, salesType, cause, issueDt, flag, addDt) " + _
                "   VALUES('" + valSessionKey + "','" + valPrdCd + "','" + valTotalQty + "','" + valUnitPrice + "','" + valTotalAmount + "','" + valCompCd + "','" + valMemId + "','" + valDCRate + "','" + valDCAmount + "','" + valAmount + "','" + valOrgAmount + "','" + valTax + "','" + valBoxQty + "','" + valSalesType + "', '" + valCmbCause + "', '" + valIssueDt + "','" + valCmbFlag + "','" + curDt + "')"
            rtnMsg = "판매 정보가 추가되었습니다"
        Else
            sql = "UPDATE tblPrdOutTMP SET [output]='" + valTotalQty + "', prdCd='" + valPrdCd + "', compCd='" + valCompCd + "', unitPrice='" + valUnitPrice + "', totalPrice='" + valTotalAmount + "', memId='" + valMemId + "', dcRate='" + valDCRate + "', dcAmount='" + valDCAmount + "', amount='" + valAmount + "', orgAmount='" + valOrgAmount + "', tax='" + valTax + "', boxQty='" + valBoxQty + "', salesType='" + valSalesType + "', issueDt='" + valIssueDt + "', flag='" + valCmbFlag + "', updateDt='" + curDt + "' WHERE seq=" + txtTmpSeq.Text
            rtnMsg = "판매 정보가 수정되었습니다"
        End If

        oleCmd = New OleDb.OleDbCommand(sql, dbConn)

        oleTran = dbConn.BeginTransaction
        oleCmd.Transaction = oleTran
        Try

            oleCmd.ExecuteNonQuery()
            oleTran.Commit()

            dbConn.Close()
            MsgBox(rtnMsg)
            Call gridRefresh()
            Call txtReset()
        Catch err As OleDb.OleDbException
            oleTran.Rollback()
            dbConn.Close()
            MsgBox(sql)

            MsgBox(err.Message, MsgBoxStyle.Critical, "오류")
        End Try
    End Sub

    '## 전체 값 구하기
    Private Sub getAllPrice()
        If autoCount = False Then
            Exit Sub
        End If
        Dim valTotalAmount As Double = 0
        Dim valDCAmount As Double = 0
        Dim valAmount As Double = 0
        Dim valTax As Double = 0
        Dim valOrgAmount As Double = 0
        If txtUnitPrice.Text = "" Then
            txtUnitPrice.Text = 0
        End If
        If txtTotalQty.Text = "" Then
            txtTotalQty.Text = 0
        End If
        If txtTotalAmount.Text = "" Then
            txtTotalAmount.Text = 0
        End If

        If cmbCause.IsHandleCreated = True Then
            If cmbCause.SelectedValue.ToString <> "판매" Then
                txtUnitPrice.Text = 0
            End If
        End If
        valTotalAmount = CInt(txtUnitPrice.Text) * CInt(txtTotalQty.Text)
        txtTotalAmount.Text = valTotalAmount
        'MsgBox(valTotalAmount)

        If txtDCRate.Text <> "" And txtDCRate.Text <> "0" Then
            valDCAmount = CInt(txtTotalAmount.Text) * CInt(txtDCRate.Text) * 0.01
            txtDCAmount.Text = valDCAmount
        Else
            If txtDCAmount.Text <> "" Then
                valDCAmount = txtDCAmount.Text
            End If
        End If

        valAmount = CInt(valTotalAmount) - valDCAmount
        txtAmount.Text = valAmount
        valTax = CInt(valAmount / 11)
        txtTax.Text = valTax
        txtOrgAmount.Text = CInt(valAmount) - CInt(valTax)
        txtUnitPrice.Text = Format(CInt(txtUnitPrice.Text), "#,##0")
        txtDCRate.Text = Format(CInt(txtDCRate.Text), "#,##0")
        txtDCAmount.Text = Format(CInt(txtDCAmount.Text), "#,##0")
        txtTotalQty.Text = Format(CInt(txtTotalQty.Text), "#,##0")
        txtTotalAmount.Text = Format(CInt(txtTotalAmount.Text), "#,##0")
        txtAmount.Text = Format(CInt(txtAmount.Text), "#,##0")
        txtTax.Text = Format(CInt(txtTax.Text), "#,##0")
        txtOrgAmount.Text = Format(CInt(txtOrgAmount.Text), "#,##0")

    End Sub
#End Region

#Region "라이브러리 함수"

    '## 출고 사유
    Public Sub mkCmbOutCause()
        Dim sql As String
        'Call dbConnection()
        sql = "SELECT itemNm, itemCd FROM tblComCode WHERE flag='Y' AND groupCd='0010' ORDER BY itemSeq"
        dsSales = New DataSet
        daSales = New OleDb.OleDbDataAdapter(sql, dbConn)
        daSales.Fill(dsSales, "cmbCause")

        With cmbCause
            .DataSource = dsSales.Tables("cmbCause")
            .DisplayMember = "itemNm"
            .ValueMember = "itemNm"
        End With
        cmbCause.SelectedIndex = 0
    End Sub

    '## 회원정보 가져오기
    Private Sub mkCmbMember(ByVal memNm As String)
        Dim addSql As String = ""
        Dim dsSalesMem As DataSet
        Dim daSalesMem As OleDb.OleDbDataAdapter

        If memNm <> "" Then
            salesPrdCdChangeActionOn = True
            addSql = "WHERE memNm LIKE '%" + memNm + "%' AND flag='Y' "
        End If
        sql = "SELECT memNm, memId FROM tblMember " + addSql + " ORDER BY memNm"
        dsSalesMem = New DataSet
        daSalesMem = New OleDb.OleDbDataAdapter(sql, dbConn)
        daSalesMem.Fill(dsSalesMem, "Mem")
        dbConn.Close()

        Dim newDsRow As DataRow = dsSalesMem.Tables("Mem").NewRow
        newDsRow("memNm") = "-회원-"
        newDsRow("memId") = "0"

        dsSalesMem.Tables("Mem").Rows.Add(newDsRow)

        Try
            With cmbMember
                .DataSource = dsSalesMem.Tables("Mem")
                .DisplayMember = "memNm"
                .ValueMember = "memId"
                '.SelectedIndex = 0
            End With
            If addSql = "" Then
                cmbMember.SelectedIndex = dsSalesMem.Tables("Mem").Rows.Count - 1
            End If
        Catch err As NullReferenceException
            MsgBox(err.Message)
        End Try
    End Sub

    '## 실시간 제품 단가 가져오기
    Private Sub getUnitPirce()
        If autoCount = False Then
            Exit Sub
        End If
        Dim BCFlag As String
        If radB2C.Checked = True Then
            BCFlag = "B2C"
        Else
            BCFlag = "B2B"
        End If
        If salesPrdCdChangeActionOn = True Then
            If cmbPrdCd.SelectedValue.ToString <> "0" Then
                txtUnitPrice.Text = gFnUnitPrice(BCFlag, cmbPrdCd.SelectedValue.ToString)
            Else
                txtUnitPrice.Text = 0
            End If

        End If
    End Sub

    '## 제품 가져오기
    Private Sub mkCmbProduct(ByVal val As String)
        Dim sql As String
        Dim dsSales As DataSet
        Dim daSales As OleDb.OleDbDataAdapter
        Dim addSql As String = ""
        salesPrdCdChangeActionOn = False
        'Call dbConnection()
        If val <> "" Then
            salesPrdCdChangeActionOn = True
            addSql = "WHERE prdNm LIKE '%" + val + "%' AND flag='Y' "
        End If
        sql = "SELECT prdNm as product, prdCd FROM tblProduct " + addSql + " ORDER BY prdNm"
        dsSales = New DataSet
        daSales = New OleDb.OleDbDataAdapter(sql, dbConn)
        daSales.Fill(dsSales, "PRD")

        Dim newDsRow As DataRow = dsSales.Tables("PRD").NewRow
        newDsRow("product") = "-제품-"
        newDsRow("prdCd") = "0"

        dsSales.Tables("PRD").Rows.Add(newDsRow)

        Try
            With cmbPrdCd
                .DataSource = dsSales.Tables("PRD")
                .DisplayMember = "product"
                .ValueMember = "prdCd"
                '.SelectedIndex = 0
            End With
            If addSql = "" Then
                cmbPrdCd.SelectedIndex = dsSales.Tables("PRD").Rows.Count - 1
            End If
        Catch err As NullReferenceException
            MsgBox(err.Message)
        End Try
        salesPrdCdChangeActionOn = True
    End Sub

    '## 박스당 갯수 구하는 함수
    Private Sub getEaOnBox()
        If autoCount = False Then
            Exit Sub
        End If
        If radSalesUnit2.Checked = True Then
            If cmbPrdCd.SelectedValue.ToString <> "0" Then
                txtTotalQty.Text = gFnEaOnBox(txtQty.Text, cmbPrdCd.SelectedValue.ToString)
            End If
        Else
            txtTotalQty.Text = txtQty.Text
        End If
    End Sub

    '## 거래처 가져오기
    Public Sub mkCmbCompany(ByVal val As String, ByVal obj As Object)
        Dim addSql As String = ""

        If val <> "" Then
            addSql = "WHERE company LIKE '%" + val + "%' AND flag='Y' "
        End If
        sql = "SELECT company+'('+compNo+')' as compInfo, compCd FROM tblCompany " + addSql + " ORDER BY company"
        dsSales = New DataSet
        daSales = New OleDb.OleDbDataAdapter(sql, dbConn)
        daSales.Fill(dsSales, "comp")

        dbConn.Close()
        Dim newDsRow As DataRow = dsSales.Tables("comp").NewRow
        newDsRow("compInfo") = "-거래처-"
        newDsRow("compCd") = "0"

        dsSales.Tables("comp").Rows.Add(newDsRow)

        Try
            With obj
                .DataSource = dsSales.Tables("comp")
                .DisplayMember = "compInfo"
                .ValueMember = "compCd"
                '.SelectedIndex = 0
            End With
            If addSql = "" Then
                obj.SelectedIndex = dsSales.Tables("comp").Rows.Count - 1
            End If
        Catch err As NullReferenceException
            MsgBox(err.Message)
        End Try
    End Sub
#End Region

End Class